package tankgame03;

import java.io.*;

/**
 * @author DCSGO
 * @version 1.0
 * 记分器 记录积分并保存到文件
 */
public class Recorder {
    private static int integral;
    private static final String filePath = "src\\myRecorder.dat";

    public static void bonusPoints() {
        integral++;
    }

    static {//静态代码块 初始化 Recorder 从文件读取积分
        File myRecorder;
        ObjectInputStream ois = null;
        try {
            myRecorder = new File(filePath);
            if (myRecorder.exists() && myRecorder.canRead()) {
                ois = new ObjectInputStream(new FileInputStream(myRecorder));
                integral = ois.readInt();
            } else {
                if (myRecorder.createNewFile()) {
                    System.out.println(myRecorder.getName() + "不存在 创建新文件成功");
                    integral = 0;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            integral = 0;
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.getStackTrace();
            }
        }
    }

    public static void save() {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(filePath));
            oos.writeInt(integral);
        } catch (IOException e) {
            e.getStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.getStackTrace();
            }
        }
    }

    public static int getIntegral() {
        return integral;
    }
}
